package chat.servlets;

import chat.Message;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ChatServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	public void init() throws ServletException
	{
		super.init();
		Vector<Message> messages = new Vector<Message>();
		getServletContext().setAttribute("messages", messages);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter responseWriter = response.getWriter();

		Vector<Message> messages = (Vector<Message>) getServletContext().getAttribute("messages");

		responseWriter.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		responseWriter.print("<newmessages>");

		int currentMessageNumber = Integer.parseInt(request.getParameter("currentMessageNumber"));

		for (int i = currentMessageNumber; i < messages.size(); i++)
		{
			responseWriter.println("<message>");
			
			responseWriter.println("<username>" + messages.get(i).getUsername() + "</username>");
			responseWriter.println("<text>" + messages.get(i).getText() + "</text>");
			responseWriter.println("<time>" + messages.get(i).getTime() + "</time>");
			
			responseWriter.println("</message>");
		}

		responseWriter.print("<messageCountGlobal>" + messages.size() + "</messageCountGlobal>");
		responseWriter.print("</newmessages>");
		responseWriter.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		response.setContentType("text/xml;charset=UTF-8");
		PrintWriter responseWriter = response.getWriter();

		Vector<Message> messages = (Vector<Message>) getServletContext().getAttribute("messages");

		responseWriter.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
		responseWriter.print("<sendingstatus>");

		if (request.getParameter("username") != null && request.getParameter("message") != null)
		{
			messages.addElement(new Message(request.getParameter("username").toString(), request.getParameter("message").toString()));
			getServletContext().setAttribute("messages", messages);
			responseWriter.print("<ok/>");
		}
		else
			responseWriter.print("<failed/>");
		
		responseWriter.print("</sendingstatus>");
		responseWriter.close();
	}

	public String getServletInfo()
	{
		return "Chat Servlet";
	}
}